<template>
  <view class="order-list">
    <ExtractOrderFilter @filterChange="handleFilterChange" />
    <InfiniteList ref="infiniteListRef" :pageNo="pageNo - 1" :limit="limit" @loadData="loadmore">
      <template #default="{ item, index }">
        <view class="order-card" @click="handleDetail(item)">
          <wd-card type="rectangle">
            <template #title>
              <view class="title">
                <view>订单号：{{ item.orderNo }}</view>
              </view>
            </template>
            <view class="content">
              <wd-cell-group>
                <wd-cell
                  title="创建时间"
                  :value="dayjs(item.createTime).format('YYYY-MM-DD HH:mm:ss')"
                />
                <wd-cell title="客户名称" :value="item.farmerName" />
                <wd-cell title="工厂名称" :value="item.factoryName" />
                <wd-cell title="提油类型">
                  <dictItem dict-code="oil_withdrawal_type" :value="item.oilWithdrawalType" />
                </wd-cell>
                <wd-cell title="提油方式">
                  <dictItem dict-code="oil_withdrawal_way" :value="item.oilWithdrawalWay" />
                </wd-cell>
              </wd-cell-group>
            </view>

            <template #footer>
              <view class="footer">
                <view class="left">
                  <!-- <wd-button size="small" @click="handleDetail(item)">查看详情</wd-button> -->
                  <view round class="pending" v-if="item.isPending === 'Y'">待处理</view>
                  <view round class="order-status">
                    <dictItem dict-code="get_oil_order_status" :value="item.status" />
                  </view>
                </view>
                <view class="right"></view>
              </view>
            </template>
          </wd-card>
        </view>
      </template>
    </InfiniteList>
  </view>
</template>

<script setup lang="ts">
import { useToast } from 'wot-design-uni'
import { http } from '@/utils/http'
import { extractOrderApi, userApi } from '@/api/api'
import dayjs from 'dayjs'
import { useUserStore } from '@/store/user'
import { extractMethods, extractTypes, extractOrderStatus } from '@/common/constants'
import ExtractOrderFilter from './extractOrderFilter.vue'
import InfiniteList from '@/components/List/InfiniteList.vue'
import { useRouter } from '@/plugin/uni-mini-router'
import dictItem from '@/components/dictItem/dictItem.vue'

defineOptions({
  options: {
    styleIsolation: 'shared',
  },
})
const userStore = useUserStore()

// 启用下拉刷新
onPullDownRefresh(() => {
  onRefresh()
})
// 初始化工具和状态
const toast = useToast()
const router = useRouter()

const infiniteListRef = ref<InstanceType<typeof InfiniteList>>()

const userRole = ref('') // 'factory' 或 'grower'
const userRoleName = userStore.userInfo.userRoleName
const tenantId = userStore.userInfo.tenantId
if (userRoleName && (userRoleName.includes('工厂') || userRoleName.includes('管理员'))) {
  userRole.value = 'factory'
} else {
  userRole.value = 'grows'
}

const pageNo = ref(1)
const limit = ref(10)
const params = reactive({})

/**
 * 加载更多数据
 * 1. 模拟异步请求数据
 * 2. 设置总条数和当前页数据
 * 3. 根据数据状态更新列表状态
 * @param {number} pageIndex - 当前页码
 * @param {number} limit - 每页数据条数
 */
async function loadmore(pageIndex, limit) {
  const url = extractOrderApi.query
  const res = await http.post(url, {
    pageNo: pageIndex,
    pageSize: limit,
    ...params,
    tenantId: tenantId ? tenantId : '',
  })
  if (res.success) {
    console.log('res.data', res.data)
    const data = res.result
    const newList = data.records || []
    infiniteListRef.value.setTotal(data.total)
    infiniteListRef.value.setList(newList)
    if (infiniteListRef.value.getList().length >= data.total) {
      infiniteListRef.value.setState('finished') // 数据加载完成
    } else {
      infiniteListRef.value.setState('loading') // 数据加载中
    }
  } else {
    infiniteListRef.value.setState('error') // 数据加载失败
    toast.error(res?.message || '数据加载失败！')
  }
}

// 下拉刷新
function onRefresh() {
  pageNo.value = 1
  infiniteListRef.value.clearList()
  loadmore(pageNo.value, limit.value)
  uni.stopPullDownRefresh()
}

// 是否显示待处理
function isShowPending(item) {
  // 待接单、运输中、待质检、待确认质检、待入库、待确认得油结果 状态显示待处理
  return ['C', 'E', 'F', 'I', 'H', 'K'].includes(item.status)
}

/**
 * 查看详情
 * @param {Object} item - 订单项
 */
function handleDetail(item) {
  console.log(item)
  router.push({
    name: 'ExtractOrder',
    params: {
      orderId: item.id,
    },
  })
}

/**
 * 取消订单
 */
function handleCancel(item) {
  console.log(item)
  // 添加取消弹窗
  uni.showModal({
    title: '取消',
    content: '确认取消订单？',
    success: function (res) {
      if (res.confirm) {
        console.log('用户点击确定')
        // 在这里执行删除操作
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}
/**
 * 提交订单
 */
function handleSubmit(item) {
  console.log(item)
  uni.showModal({
    title: '提交',
    content: '确认提交订单？',
    success: function (res) {
      if (res.confirm) {
        console.log('用户点击确定')
        // 在这里执行删除操作
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}

// 根据订单状态判断按钮是否需要显示
const shouldShowButton = (item, buttonName: string): boolean => {
  const status = item.status
  switch (status) {
    case 'A': // 待提交
      return ['暂存', '提交', '删除'].includes(buttonName)
    case 'I': // 待确认质检
      return buttonName === '质检结果确认'
    case 'K': // 待确认得油结果
      return buttonName === '得油结果确认'
    case 'M': // 待付款
      return buttonName === '付款'
    default:
      return false
  }
}

// 删除订单
const deleteOrder = async (item) => {
  uni.showModal({
    title: '删除',
    content: '确认删除订单？',
    success: async function (res) {
      if (res.confirm) {
        try {
          const res = await http.post(orderApi.deleteOrder, { id: item.id })
          if (res.success) {
            toast.success('删除成功')
            infiniteListRef.value.clearList() // 清空当前列表
            loadmore(pageNo.value, limit.value) // 重新加载数据
          } else {
            toast.error(res?.message || '删除失败！')
          }
        } catch (error) {
          toast.error('删除失败')
        }
        // 在这里执行删除操作
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    },
  })
}

/**
 * 筛选条件变化
 */
function handleFilterChange(val) {
  console.log('筛选条件：', val)
  Object.assign(params, val)
  // 根据时间范围重新加载数据
  infiniteListRef.value.clearList() // 清空当前列表
  loadmore(pageNo.value, limit.value) // 重新加载数据
}

onShow(() => {
  onRefresh()
})
</script>
<style scoped lang="scss">
.order-list {
  padding-bottom: 60px;

  .order-card {
    margin: 20px;
    :deep(.wd-card) {
      border-radius: 8px;
      overflow: hidden;
      .wd-cell__wrapper {
        padding: 0;
      }
    }
    .title {
      display: flex;
      justify-content: space-between;
    }
    .content {
      .wd-cell {
        padding-left: 0;
        .wd-cell__wrapper {
          padding: 5px 0;
        }
      }
    }
    .footer {
      display: flex;
      justify-content: space-between;
      .left {
        display: flex;
        gap: 10px;
        .order-status {
          background-color: #fff0f6;
          color: #ed47a3;
          border: 1px solid #ed47a3;
          border-radius: 4px;
          padding: 3px 5px;
        }
        .pending {
          background-color: #fff0e6;
          color: #ff5500;
          border: 1px solid #ff5500;
          border-radius: 4px;
          padding: 3px 5px;
        }
      }
      .right {
        display: flex;
        gap: 10px;
      }
    }
  }
}
</style>
